// src/components/ItemList.jsx
import React, { useEffect, useState, useMemo } from "react";
import Sidebar from "../Sidebar";
import Navbar from "../Navbar";
import { BiChevronRight } from "react-icons/bi";
import { FaTachometerAlt, FaEdit, FaTrash } from "react-icons/fa";
import { Link, NavLink, useNavigate } from "react-router-dom";
import axios from "axios";
import Select from "react-select";
import LoadingScreen from "../../Loading";

const FILES_BASE = "https://mybackend-l7om.onrender.com/uploads/qr/items";

export default function ItemList() {
  const navigate = useNavigate();

  /* ───────── UI state ───────── */
  const [isSidebarOpen, setSidebarOpen] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  /* ───────── Data ───────── */
  const [items, setItems] = useState([]);
  const [unitOptions, setUnitOptions] = useState([]);
  const [warehouseOptions, setWarehouseOptions] = useState([]);

  /* ───────── Filters ───────── */
  const [warehouseFilter, setWarehouseFilter] = useState("all");
  const [unitFilter, setUnitFilter] = useState("all");

  /* ───────── Pagination ───────── */
  const [currentPage, setCurrentPage] = useState(1);
  const entriesPerPage = 10;

  /* ───────── Dropdown & Preview ───────── */
  const [dropdownOpenFor, setDropdownOpenFor] = useState(null);
  const [previewItem, setPreviewItem] = useState(null);

  /* ───────── Remove‐Image Popup ───────── */
  const [popupImage, setPopupImage] = useState(null);
  const [popupIndex, setPopupIndex] = useState(null);

  /* ───────── Axios Auth Header ───────── */
  const auth = () => ({
    headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
  });

  /* ───────── Fetch All Items ───────── */
  const fetchItems = async () => {
    setLoading(true);
    setError(null);
    try {
      const { data } = await axios.get("https://mybackend-l7om.onrender.com/api/items", auth());
      const itemsArray = Array.isArray(data.data) ? data.data : [];
      console.log(
        "Fetched items:",
        itemsArray.map((item) => ({
          name: item.itemName,
          itemImages: item.itemImages,
        }))
      );
      setItems(itemsArray);
    } catch (err) {
      console.error("Error fetching items:", err);
      setError("Failed to fetch items. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  /* ───────── Fetch Units for Filter ───────── */
  const fetchUnits = async () => {
    try {
      const { data } = await axios.get("https://mybackend-l7om.onrender.com/api/units", auth());
      const options = [
        { label: "All", value: "all" },
        ...data.data.map((u) => ({ label: u.unitName, value: u._id })),
      ];
      return options;
    } catch (err) {
      console.error("Error fetching units:", err);
      return [{ label: "All", value: "all" }];
    }
  };

  /* ───────── Fetch Warehouses for Filter ───────── */
  const fetchWarehouses = async () => {
    try {
      const { data } = await axios.get("https://mybackend-l7om.onrender.com/api/warehouses", auth());
      const options = [
        { label: "All Warehouses", value: "all" },
        ...data.data.map((w) => ({ label: w.warehouseName, value: w._id })),
      ];
      return options;
    } catch (err) {
      console.error("Error fetching warehouses:", err);
      return [{ label: "All Warehouses", value: "all" }];
    }
  };

  /* ───────── Delete an Item ───────── */
  const handleDelete = async (id) => {
    if (!window.confirm("Do you really want to delete this item?")) return;
    setLoading(true);
    setError(null);
    try {
      await axios.delete(`https://mybackend-l7om.onrender.com/api/items/${id}`, auth());
      alert("Deleted successfully");
      await fetchItems();
    } catch (err) {
      console.error("Error deleting item:", err);
      setError("Failed to delete item. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  /* ───────── Initialize on Mount ───────── */
  useEffect(() => {
    if (window.innerWidth < 768) setSidebarOpen(false);
    fetchItems();
    fetchUnits().then((options) => {
      console.log("Unit options:", options);
      setUnitOptions(options);
    });
    fetchWarehouses().then((options) => {
      console.log("Warehouse options:", options);
      setWarehouseOptions(options);
    });
  }, []);

  /* ───────── Thumbnail Click → Open Confirmation Popup ───────── */
  const onThumbnailClick = (filename, idx) => {
    setPopupImage(filename);
    setPopupIndex(idx);
  };

  /* ───────── Remove Image from Item ───────── */
  const handleRemoveImage = async (index) => {
    if (!previewItem) return;

    // 1. Remove from in‐memory previewItem
    const updatedFilenames = [...previewItem.itemImages];
    const removedFile = updatedFilenames.splice(index, 1)[0];

    setPreviewItem({
      ...previewItem,
      itemImages: updatedFilenames,
    });

    // 2. Also update the items array so the table row updates
    setItems((old) =>
      old.map((it) =>
        it._id === previewItem._id
          ? { ...it, itemImages: updatedFilenames }
          : it
      )
    );

    // 3. Call backend to persist removal
    try {
      await axios.delete(
        `https://mybackend-l7om.onrender.com/api/items/${previewItem._id}/images/${removedFile}`,
        auth()
      );
      // Optionally re‐fetch items: await fetchItems();
    } catch (err) {
      console.error("Failed to remove image on server:", err);
      // Optionally revert local state or show error
      setError("Failed to remove image from server. Please reload.");
    }
  };

  /* ───────── Filtered + Paginated List ───────── */
  const filtered = useMemo(() => {
    return items.filter((item) => {
      const okWh = warehouseFilter === "all" || item.warehouse?._id === warehouseFilter;
      const okUnit = unitFilter === "all" || item.unit?._id === unitFilter;
      return okWh && okUnit;
    });
  }, [items, warehouseFilter, unitFilter]);

  const totalPages = Math.ceil(filtered.length / entriesPerPage);
  const pageStart = (currentPage - 1) * entriesPerPage;
  const pageSlice = filtered.slice(pageStart, pageStart + entriesPerPage);

  /* ───────── Render Loading / Error ───────── */
  if (loading) return <LoadingScreen />;
  if (error) return <div className="p-4 text-red-600">{error}</div>;

  return (
    <div className="flex flex-col h-screen">
      <Navbar isSidebarOpen={isSidebarOpen} setSidebarOpen={setSidebarOpen} />
      <div className="flex flex-grow">
        <Sidebar isSidebarOpen={isSidebarOpen} />
        <div className="flex-grow p-4 mt-20">
          {/* ───────── Header / Breadcrumbs ───────── */}
          <header className="flex flex-col md:flex-row justify-between mb-6">
            <h2 className="text-2xl font-bold">Items List</h2>
            <nav className="flex text-gray-600 gap-2 mt-2 md:mt-0">
              <NavLink to="/dashboard" className="flex items-center">
                <FaTachometerAlt /> Home
              </NavLink>
              <BiChevronRight />
              <NavLink to="/item-list">Items List</NavLink>
            </nav>
          </header>

          {/* ───────── Filters ───────── */}
          <div className="mb-4 p-4 bg-white rounded shadow flex flex-col md:flex-row justify-between gap-4">
            <div className="flex gap-4 flex-wrap">
              <div className="w-48">
                <label className="block mb-1">Warehouse</label>
                <Select
                  options={warehouseOptions}
                  value={
                    warehouseOptions.find((o) => o.value === warehouseFilter) ||
                    { label: "All Warehouses", value: "all" }
                  }
                  onChange={(o) => setWarehouseFilter(o.value)}
                />
              </div>
              <div className="w-48">
                <label className="block mb-1">Unit</label>
                <Select
                  options={unitOptions}
                  value={
                    unitOptions.find((o) => o.value === unitFilter) || {
                      label: "All",
                      value: "all",
                    }
                  }
                  onChange={(o) => setUnitFilter(o.value)}
                />
              </div>
            </div>
            <div className="flex gap-2">
              <Link to="/items/add">
                <button className="px-4 py-2 bg-cyan-500 text-white rounded">
                  + Create Item
                </button>
              </Link>
              <Link to="/services/add">
                <button className="px-4 py-2 bg-green-600 text-white rounded">
                  + Create Service
                </button>
              </Link>
            </div>
          </div>

          {/* ───────── Table ───────── */}
          <div className="overflow-x-auto bg-white rounded shadow">
            <table className="w-full text-sm border-collapse">
              <thead>
                <tr className="bg-gray-200">
                  {[
                    "Image",
                    "Code",
                    "Name",
                    "Brand",
                    "Category",
                    "Unit",
                    "Stock",
                    "Alert Qty",
                    "Sales Price",
                    "Tax",
                    "Status",
                    "Action",
                  ].map((h) => (
                    <th key={h} className="px-2 py-1 border">
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>

              <tbody>
                {pageSlice.length ? (
                  pageSlice.map((item) => {
                    const fileName = item.itemImages?.[0];
                    const imgUrl = fileName ? `${FILES_BASE}/${fileName}` : null;

                    return (
                      <tr key={item._id}>
                        <td className="border px-2 py-1 text-center">
                          {fileName ? (
                            <img
                              src={imgUrl}
                              alt={item.itemName}
                              className="w-10 h-10 object-cover mx-auto cursor-pointer hover:opacity-80"
                              onClick={() => setPreviewItem(item)}
                            />
                          ) : (
                            <span className="text-gray-400">No image</span>
                          )}
                        </td>
                        <td className="border px-2 py-1">{item.itemCode}</td>
                        <td className="border px-2 py-1">{item.itemName}</td>
                        <td className="border px-2 py-1">
                          {item.brand?.brandName || "NA"}
                        </td>
                        <td className="border px-2 py-1">
                          {item.category?.name || "NA"}
                        </td>
                        <td className="border px-2 py-1">
                          {item.unit?.unitName || "NA"}
                        </td>
                        <td className="border px-2 py-1 text-center">
                          {item.openingStock}
                        </td>
                        <td className="border px-2 py-1 text-center">
                          {item.alertQuantity}
                        </td>
                        <td className="border px-2 py-1 text-right">
                          {item.salesPrice}
                        </td>
                        <td className="border px-2 py-1">
                          {item.tax?.taxName || "NA"}
                        </td>
                        <td className="border px-2 py-1 text-center">
                          <span className="px-2 py-1 bg-green-600 text-white rounded">
                            Active
                          </span>
                        </td>
                        <td className="border px-2 py-1 relative">
                          <button
                            onClick={() =>
                              setDropdownOpenFor(
                                dropdownOpenFor === item._id
                                  ? null
                                  : item._id
                              )
                            }
                            className="px-2 py-1 bg-cyan-600 text-white rounded"
                          >
                            Action ▼
                          </button>
                          {dropdownOpenFor === item._id && (
                            <div className="absolute right-0 mt-1 bg-white border rounded shadow z-50">
                              <button
                                className="flex items-center w-full px-3 py-2 hover:bg-gray-100"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  navigate(
                                    `/items/add?id=${item.parentItemId || item._id}`
                                  );
                                }}
                              >
                                <FaEdit className="mr-2" /> Edit
                              </button>
                              <button
                                className="flex items-center w-full px-3 py-2 text-red-600 hover:bg-gray-100"
                                onClick={() => handleDelete(item._id)}
                              >
                                <FaTrash className="mr-2" /> Delete
                              </button>
                            </div>
                          )}
                        </td>
                      </tr>
                    );
                  })
                ) : (
                  <tr>
                    <td colSpan="12" className="py-4 text-center">
                      No data available
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {/* ───────── Pagination ───────── */}
          <div className="flex justify-between items-center mt-4 px-2">
            <span>
              Showing {pageStart + 1} to{" "}
              {Math.min(pageStart + entriesPerPage, filtered.length)} of{" "}
              {filtered.length} entries
            </span>
            <div className="space-x-2">
              <button
                onClick={() => setCurrentPage((p) => Math.max(p - 1, 1))}
                disabled={currentPage === 1}
                className="px-3 py-1 bg-gray-300 rounded disabled:opacity-50"
              >
                Previous
              </button>
              <button
                onClick={() => setCurrentPage((p) => Math.min(p + 1, totalPages))}
                disabled={currentPage === totalPages}
                className="px-3 py-1 bg-gray-300 rounded disabled:opacity-50"
              >
                Next
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* ───────── Image Preview + Removal Modal ───────── */}
      {previewItem && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70"
          onClick={() => {
            setPreviewItem(null);
            setPopupImage(null);
          }}
        >
          <div
            className="bg-white rounded shadow-lg max-w-4xl w-full max-h-[90vh] p-4 overflow-auto relative"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-semibold">
                {previewItem.itemName} – images
              </h3>
              <button
                className="text-red-600 text-2xl font-bold"
                onClick={() => {
                  setPreviewItem(null);
                  setPopupImage(null);
                }}
              >
                &times;
              </button>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
              {previewItem.itemImages.map((fn, idx) => {
                const url = fn.startsWith("http") ? fn : `${FILES_BASE}/${fn}`;
                return (
                  <div key={idx} className="relative group">
                    <img
                      src={url}
                      alt={`${previewItem.itemName} ${idx + 1}`}
                      className="w-full h-64 object-cover rounded cursor-pointer"
                      onError={(e) => {
                        e.currentTarget.src = "https://via.placeholder.com/150";
                      }}
                      onClick={() => onThumbnailClick(fn, idx)}
                    />
                  </div>
                );
              })}
            </div>

            {/* ───────── Confirmation Popup ───────── */}
            {popupImage && (
              <div
                className="fixed inset-0 z-60 flex items-center justify-center bg-black/50"
                onClick={() => setPopupImage(null)}
              >
                <div
                  className="bg-white rounded-lg p-6 shadow-lg max-w-sm w-full"
                  onClick={(e) => e.stopPropagation()}
                >
                  <h4 className="text-lg font-semibold mb-4">
                    Remove this image?
                  </h4>
                  <p className="text-sm mb-6 text-gray-700">
                    Are you sure you want to remove{" "}
                    <span className="font-medium">{popupImage}</span>?
                  </p>
                  <div className="flex justify-end gap-2">
                    <button
                      className="px-4 py-2 bg-gray-300 rounded hover:bg-gray-400"
                      onClick={() => setPopupImage(null)}
                    >
                      Cancel
                    </button>
                    <button
                      className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
                      onClick={() => {
                        handleRemoveImage(popupIndex);
                        setPopupImage(null);
                      }}
                    >
                      Yes, Remove
                    </button>
                  </div>
                </div>
              </div>
            )}
            {/* ───────── end Confirmation Popup ───────── */}
          </div>
        </div>
      )}
    </div>
  );
}
